package com.quan.system.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;


/**
 * Redis 监听过期事件
 * 使用这个的前提是配置文件要开启事件监听：notify-keyspace-events Ex
 * 1、需修改配置文件，将“notify-keyspace-events Ex”注释打开
 * 2、配置一个RedisListenerConfig配置类
 * 3、编写下面监听器
 * 过期监听消息中返回的是，过期的键的key值，是没有返回value的
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    protected void doHandleMessage(Message message) {
        String channel = new String(message.getChannel());
        if (channel.equals("__keyevent@0__:expired")) {
            String body = new String(message.getBody());
            log.info("Redis 消息过期：ID：{}", body);
            final String[] split = body.split(":");
            final String userId = split[split.length - 1].toString();
        }

    }
}
